from django.shortcuts import render

# Create your views here.
import re
import random
import logging
from django_redis import get_redis_connection
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status as http_status
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated

from luffyapi.libs.geetest import GeetestLib
from luffyapi.settings import constants
from luffyapi.libs.yuntongxun.sendtemplatesms import YunTongXin
from .utils import get_user_by_account
from .models import User
from .serializers import UserModelSerializer,UserOrderModelSerializer
from mycelery.sms.tasks import send_sms

from order.models import Order

log = logging.getLogger("django")
pc_geetest_id = "5e876edb2bda195c265416b70e7389a7"
pc_geetest_key = "c1f0f6f5958507924d187db31cd136e5"


class CaptchaAPIView(APIView):
    """验证码视图类"""
    status = False
    user_id = 0

    def get(self, request):
        """获取验证码"""
        username = request.query_params.get("username")
        user = get_user_by_account(username)
        if user is None:
            return Response({"message": "对不起，用户不存在！"}, status=http_status.HTTP_400_BAD_REQUEST)

        self.user_id = user.id
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        self.status = gt.pre_process(self.user_id)
        # todo 后面增加status和user_id保存到redis数据库
        response_str = gt.get_response_str()
        return Response(response_str)

    def post(self, request):
        """验证码的验证方法"""
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        if self.status:
            result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)


class UserAPIView(CreateAPIView):
    """ 用户信息视图 """
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class MobileAPIView(APIView):
    """
    要不要序列话器都行
    不要序列化器可以先继承 APIView
    """

    def get(self, request, mobile):
        # if not re.match(r"^1[3-9]\d{9}$", mobile):
        #     return Response({"message": "手机号码格式不正确"})
        ret = get_user_by_account(mobile)
        if ret is not None:
            return Response({"message": "手机号已经被注册"}, status=http_status.HTTP_400_BAD_REQUEST)
        return Response({"message": "OK"})


class SMSAPIView(APIView):
    """ 发送短信 """

    def get(self, request, mobile):
        # 1 判断手机号在60秒内是不是发送过短信
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("mobile_%s" % mobile)
        if ret is not None:
            return Response({"message": "对不起不能频繁发送短信！"}, status=http_status.HTTP_400_BAD_REQUEST)

        # 2 生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)
        # 3 保存短信验证码到redis 【方法一】

        # redis_conn.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        # redis_conn.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
        # 3 【方法二，使用事务将多条命令集中发送到redis中】
        pipe = redis_conn.pipeline()  # 创建管道对象
        pipe.multi()  # 开启事务
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        pipe.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
        pipe.execute()  # 执行事务
        # 4 发送短息
        try:
            # settings.SMS["templateId"] = constants.SMS_TEMPLATE_ID
            # yun = YunTongXin(**settings.SMS)
            # res = yun.run(mobile, sms_code)
            # if res["statusCode"] != "000000":
            #     log.error("{}发送短信失败，错误码{}".format(mobile, res["statusCode"]))
            #     return Response({"message": "发送短信失败！"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

            # 通过celery 进行发送短信
            send_sms.delay(mobile, sms_code)
        except:
            return Response({"message": "发送短信失败！"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
        # 5 响应发送短信的结果
        return Response({"message": "发送短信成功！"})


class UserOrderAPIView(ListAPIView):
    serializer_class = UserOrderModelSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Order.objects.filter(user_id=self.request.user.id)
